package com.hongkuncheng.cms.helper;

import java.util.UUID;

import com.hongkuncheng.cms.model.TokenRecord;
import org.hibernate.FactorySession;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;

/**
 * Token帮助类
 *
 * @author 洪坤成
 */
@Component
public class TokenHelper {

    public static FactorySession factorySession;

    /**
     * 获取随机凭证
     *
     * @return
     */
    public static String generate() {
        String result = UUID.randomUUID().toString();
        result = result.replaceFirst("-", "hong");
        result = result.replaceFirst("-", "kun");
        result = result.replaceFirst("-", "xin");
        result = result.replaceFirst("-", "ying");
        return SecurityHelper.aesEncrypt(result);
    }

    /**
     * 验证随机凭证
     *
     * @return
     */
    public static boolean validate(String token) {
        if (token != null && !token.isEmpty() && token.length() == 64) {
            String tokenDecrypt = SecurityHelper.aesDecrypt(token);
            if (tokenDecrypt.substring(8, 12).equals("hong") && tokenDecrypt.substring(16, 19).equals("kun") &&
                    tokenDecrypt.substring(23, 26).equals("xin") && tokenDecrypt.substring(30, 34).equals("ying")) {
                int exist = Integer.parseInt(factorySession.createCriteria(TokenRecord.class)
                        .add(Restrictions.eq("token", token))
                        .setProjection(Projections.count("id"))
                        .uniqueResult().toString());
                if (exist == 0) {
                    TokenRecord tokenrecord = new TokenRecord();
                    tokenrecord.setToken(token);
                    factorySession.save(tokenrecord);
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

}
